// 获取应用实例
const app = getApp();

Page({
  data: {
    currentCategory: 'all',
    categories: [],
    exerciseList: []
  },

  onLoad() {
    this.loadCategories();
    this.loadExerciseList();
  },

  onPullDownRefresh() {
    Promise.all([
      this.loadCategories(),
      this.loadExerciseList()
    ]).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载知识点分类
  loadCategories() {
    return app.request({
      url: '/categories',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          categories: res.data.list
        });
      }
    }).catch(() => {
      app.showError('获取分类列表失败');
    });
  },

  // 加载练习列表
  loadExerciseList() {
    app.showLoading();
    return app.request({
      url: '/exercises',
      method: 'GET',
      data: {
        categoryId: this.data.currentCategory === 'all' ? '' : this.data.currentCategory
      }
    }).then(res => {
      app.hideLoading();
      if (res.code === 0) {
        this.setData({
          exerciseList: res.data.list
        });
      }
    }).catch(() => {
      app.hideLoading();
      app.showError('获取练习列表失败');
    });
  },

  // 选择分类
  selectCategory(e) {
    const category = e.currentTarget.dataset.category;
    if (category === this.data.currentCategory) return;
    
    this.setData({
      currentCategory: category
    }, () => {
      this.loadExerciseList();
    });
  },

  // 跳转到练习
  goToExercise(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/special-exam/detail/detail?id=${id}`
    });
  }
}); 